package game 
{
	import assets.Assets;
	import flash.display.BitmapData;
	import flash.utils.Dictionary;
	import game.states.StateGame;
	import org.axgl.Ax;
	import org.axgl.AxEntity;
	import org.axgl.tilemap.AxTilemap;
	
	/**
	 * ...
	 * @author Pierre Chamberlain
	 */
	public class MyTileMap 
	{
		public static var KNOWN_TYPES:Dictionary;
		
		public var mapBackground:AxTilemap;
		public var mapForeground:AxTilemap;
		
		public function MyTileMap(pBGClass:Class, pFGClass:Class) 
		{
			initClass();
			
			mapBackground =	generateMap(pBGClass, Assets.IMG_TILE_TYPES);
			mapForeground = generateMap(pFGClass, Assets.IMG_TILE_TYPES);
			
			mapForeground.alpha = .8;
			mapForeground.getTile(1).callback =	onWaterOut;
			mapForeground.getTile(3).callback =	onWaterIn;
		}
		
		public static function initClass():void {
			if (KNOWN_TYPES) {
				return;
			}
			
			KNOWN_TYPES =	new Dictionary();
			KNOWN_TYPES[0x00ffff] =	1;
			KNOWN_TYPES[0x00ff00] =	6;
			KNOWN_TYPES[0x603913] =	2;
			KNOWN_TYPES[0x8c6239] =	8;
			KNOWN_TYPES[0x754c24] =	7;
			KNOWN_TYPES[0xff0000] =	4;
			KNOWN_TYPES[0xff8800] =	5;
			KNOWN_TYPES[0xffffff] =	0;
			KNOWN_TYPES[0x0000ff] =	3;
		}
		
		/**
		 * Generates an AxTilemap object from a Bitmap image and a SpriteSheet of tiles.
		 * 
		 * @param	pBitmapCls		The world map image to read the pixels from.
		 * @param	pTileTypesCls	The spritesheet to convert the pixels to tiles.
		 * @return
		 */
		private function generateMap(pBitmapCls:Class, pTileTypesCls:Class):AxTilemap
		{
			var tileMap:AxTilemap =	new AxTilemap();
			
			//Instantiate the Bitmap, and store it's BitmapData
			var theBitmap:BitmapData =	new pBitmapCls().bitmapData;
			var theData:Array =			[];
			var rowData:Array =			[];
			
			var x:int, y:int;
			for (y = 0; y < theBitmap.height; y++) {
				for (x = 0; x < theBitmap.width; x++) {
					rowData[rowData.length] = convertToTypeID(theBitmap.getPixel(x, y));
				}
				
				theData[theData.length] = rowData.join(",");
				rowData.length = 0;	//Reset row data for next loop
			}
			
			theBitmap.dispose();	//No longer required
			
			//Joined data, spritesheet image, tile width, tile height, and start ID of solid tiles
			tileMap.build(theData.join("\n"), pTileTypesCls, 16, 16, 5);
			
			return tileMap;
		}
		
		private function convertToTypeID(pixel:uint):int {
			if (KNOWN_TYPES[pixel] == null) {
				KNOWN_TYPES[pixel] =	0;
			}
			
			return KNOWN_TYPES[pixel];
		}
		
		private function onWaterIn(pA:AxEntity, pB:AxEntity):void {
			stateGame.player.isInWater = 		true;
		}
		
		private function onWaterOut(pA:AxEntity, pB:AxEntity):void {
			stateGame.player.isInWater = 		false;
		}
		
		public function get stateGame():StateGame { return Ax.state as StateGame; }
	}

}